﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PersonalAccounting.DataAccess;

namespace PersonalAccounting.Business
{
    public class QTotalsPerMonth
    {

        #region Attributes

        DateTime _from;
        DateTime _to;
        Cuenta _account;

        List<RegMonthTotal> _result;

        #endregion

        #region Properties

        public DateTime From
        {
            get { return _from; }
            set { _from = value; }
        }

        public DateTime To
        {
            get { return _to; }
            set { _to = value; }
        }

        public Cuenta Account
        {
            get { return _account; }
            set { _account = value; }
        }


        public List<RegMonthTotal> Result
        {
            get { return _result; }
        }

        #endregion


        #region Constructor

        public QTotalsPerMonth(DateTime from, DateTime to, Cuenta account)
        {
            _from = from;
            _to = to;
            _account = account;

            _result = new List<RegMonthTotal>();

            LoadData();
        }

        #endregion

        
        #region Private Methods

        private void LoadData()
        {
            DAOMovimiento dao = new DAOMovimiento();

            MonedaVO currencyVO = new MonedaVO(_account.Moneda.Codigo, _account.Moneda.Nombre, _account.Moneda.Simbolo);
            CuentaVO accountVO = new CuentaVO(_account.Codigo, currencyVO, _account.Nombre);

            foreach (MovimientoVO mov in dao.GetMovtosPeriodo(_from, _to, accountVO))
            {
                int year = mov.Fecha.Year;
                int month = mov.Fecha.Month;

                RegMonthTotal total = FindTotal(year, month);

                if (mov.Importe > 0)
                    total.AddIn(mov.Importe);
                else
                    total.AddOut(mov.Importe * -1);
            }
        }

        private RegMonthTotal FindTotal(int year, int month)
        {
            RegMonthTotal total = null;

            foreach (RegMonthTotal reg in _result)
            {
                if (reg.Year == year && reg.Month == month)
                {
                    total = reg;
                    break;
                }
            }

            if (total == null)
            {
                total = new RegMonthTotal(year, month);
                _result.Add(total);
            }

            return total;
        }

        #endregion

    }
}